#!/usr/bin/env python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import os
from ..._util import Util, CopiedAndSymlinkedDir
from ..._game import GameBase, GameSpec, MatchContext
from ..._game_straits import GameStraitForWindows, GameStraitNeedConfigDir


class CommandAndConquerRedalert(GameBase, GameStraitForWindows):

    def __init__(self, data_dir):
        GameBase.__init__(self, data_dir)

        self._addStrait(GameStraitNeedConfigDir())

        self._spec = GameSpec()
        if True:
            self._spec.windows_archs = [self.WindowsArch.WIN32]
            self._spec.windows_versions = [self.WindowsVersion.WINXP, "*"]

            self._spec.default_language = "en_US"
            self._spec.languages = [self._spec.default_language]

            self._spec.resolutions = ["640x480", "800x600", "1024x768", "1280x1024", "1600x1200", "2048x1536"]
            self._spec.can_fullscreen = True
            self._spec.can_windowed = True

            self._spec.max_cpu_cores = 1

        self._cfgFn = "REDALERT.INI"

    @property
    def spec(self):
        return self._spec

    @property
    def run_items(self):
        return ["main"]

    def get_title(self, lang):
        return "Command And Conquer Redalert"

    def _prepare(self, context):
        self._context = context
        try:
            self._targetGameDirObj = CopiedAndSymlinkedDir(os.path.join(self._context.drive_c_dirpath, "Redalert"), [self._dataDir])
            self._targetGameDirObj.symlink("", recursive=True)
            # self._targetGameDirObj.restore_from(self._context.config_dirpath, exclude=["game.ini"])

            # create config file
            cfgFnObj = _CfgFile()
            cfgFnObj.save(os.path.join(self._targetGameDirObj.path, self._cfgFn))

            # create registry keys
            self._reg = _GameRegistry(self._context.registry)
            self._reg.writeCounterStrike()                                              # FIXME: make it optional
            self._reg.writeAftermath()                                                  # FIXME: make it optional
        except BaseException:
            self._cleanup(on_error=True)
            raise

    @MatchContext.edit_or_run
    def get_language(self):
        return self._spec.default_language

    @MatchContext.run
    def apply_resolution(self, resolution):
        assert resolution in self._spec.resolutions

    @MatchContext.run
    def apply_fullscreen_or_windowed(self, fullscreen_or_windowed):
        pass

    def _commit(self):
        pass

    def _getRunInfo(self, item):
        assert not self._context.edit_or_run
        assert item == Util.listGetOnlyItem(self.run_items)

        return self.RunInfo("C:\\Redalert\\RA95.exe")

    def _cleanup(self, on_error=False):
        if hasattr(self, "_targetGameDirObj"):
            if not on_error:
                pass
            del self._targetGameDirObj
        if hasattr(self, "_context"):
            del self._context


class _CfgFile:

    def __init__(self, path):
        self._path = path

        if pathlib.Path(self._path).read_text() != self._buf.strip("\n") + "\n":
            raise ConfigError("invalid config file %s" % (path))

    def save(self, filepath=None):
        if filepath is None:
            filepath = self._path

        pathlib.Path(filepath).write_bytes(self._buf.strip("\n") + "\n")

        self._path = filepath

    _buf = """
[Sound]
Card=0
Port=3F8h
IRQ=4
DMA=-1

[Options]
HardwareFills=no
VideoBackBuffer=yes
"""


class _GameRegistry:

    _keyName = "HKEY_LOCAL_MACHINE\\Software\\Westwood\\Red Alert Windows 95 Edition"

    _resolutionToNumberDict = bidict({
        "640x480": 1,
        "800x600": 2,
        "1024x768": 3,
        "1280x960": 4,
        "1600x1200": 5,
    })

    def __init__(self, regObj):
        self._regObj = regObj
        self._regObj.add_value(self._keyName, "Name", "REG_SZ", "Red Alert Windows 95 Edition")
        self._regObj.add_value(self._keyName, "Version", "REG_DWORD", 0x7533)
        self._regObj.add_value(self._keyName, "ra95", "REG_SZ", "3.03E")

    def writeCounterStrike(self):
        self._regObj.add_value(self._keyName, "CStrikeInstalled", "REG_DWORD", 1)

    def writeAftermath(self):
        self._regObj.add_value(self._keyName, "AftermathInstalled", "REG_DWORD", 1)

    def readLang(self):
        ret = self._regObj.get_value(self._keyName, "Locale", "REG_SZ")
        for k, v in self._langDict.items():
            if v["Locale"] == ret:
                return k
        assert False

    def writeLang(self, lang):
        for k, v in self._langDict[lang].items():
            self._regObj.add_value(self._keyName, k, "REG_SZ", v)

    def readResolution(self):
        ret = self._regObj.get_value(self._keyName, "g_RacingResolution", "REG_DWORD", fallback=1)
        return self._resolutionToNumberDict.inverse[ret]

    def writeResolution(self, resolution):
        resolution = self._resolutionToNumberDict[resolution]
        self._regObj.add_value(self._keyName, "g_RacingResolution", "REG_DWORD", resolution)

